from flask import Flask, request, jsonify
import subprocess
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

app = Flask(__name__)

# 从环境变量中读取配置
NGINX_HOME_DIR = os.getenv('NGINX_HOME_DIR', '/opt/soft/nginx')
NGINX_CONF_DIR = os.getenv('NGINX_CONF_DIR', '/opt/soft/nginx/conf/vhost')
NGINX_CONF_FILE = os.getenv('NGINX_CONF_FILE', 'stand.conf.bak')
ANSIBLE_INVENTORY = os.getenv('ANSIBLE_INVENTORY', '/etc/ansible/hosts')
ANSIBLE_PLAYBOOK = os.getenv('ANSIBLE_PLAYBOOK', '/opt/ansible/yamls/switch_nginx.yml')

@app.route('/')
def index():
    return """
    <title>Nginx Configuration Switcher Tool</title>
    <h1>Nginx Configuration Switcher</h1>
    <p>Welcome to the Nginx Configuration Switcher API.</p>
    <h2>Usage</h2>
    <ul>
        <li><b>Switch to Maintenance Mode:</b> <code>POST /switch_to_maintenance</code></li>
        <li><b>Switch to Normal Mode:</b> <code>POST /switch_to_normal</code></li>
    </ul>
    <p>For more information, please refer to the <a href="https://doc.linklogis.com/books/6621d8ac88f0bb0013ba482c/view/682e84af646652424d825bbf">official documentation</a>.</p>
    """

@app.route('/switch_to_maintenance', methods=['POST'])
def switch_to_maintenance():
    try:
        subprocess.run(['ansible-playbook', ANSIBLE_PLAYBOOK, '-i', ANSIBLE_INVENTORY, '-e', f'NGINX_HOME_DIR={NGINX_HOME_DIR}','-e', f'NGINX_CONF_FILE={NGINX_CONF_FILE}', '--tags', 'maintenance', "--skip-tags",  "warning"], check=True)
        logging.info("Switched to Maintenance Mode")
        return "Switched to Maintenance Mode"
    except subprocess.CalledProcessError as e:
        logging.error(f"Failed to switch to Maintenance Mode: {e}")
        return "Failed to switch to Maintenance Mode", 500

@app.route('/switch_to_normal', methods=['POST'])
def switch_to_normal():
    try:
        subprocess.run(['ansible-playbook', ANSIBLE_PLAYBOOK, '-i', ANSIBLE_INVENTORY, '-e', f'NGINX_HOME_DIR={NGINX_HOME_DIR}', '-e', f'NGINX_CONF_FILE={NGINX_CONF_FILE}', '--tags', 'normal', "--skip-tags",  "warning"], check=True)
        logging.info("Switched to Normal Mode")
        return "Switched to Normal Mode"
    except subprocess.CalledProcessError as e:
        logging.error(f"Failed to switch to Normal Mode: {e}")
        return "Failed to switch to Normal Mode", 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
